package service

import (
	"ollama-go/dto"
	"ollama-go/entity"
	"ollama-go/query"
	"ollama-go/vo"
	"strings"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sbuilder"
	"github.com/androidsr/sc-go/sc"
	"github.com/androidsr/sc-go/sgorm"
	"github.com/androidsr/sc-go/sno"
)

var tsStepLogService *TsStepLogService

type TsStepLogService struct {
}

func NewTsStepLogService() *TsStepLogService {
	if tsStepLogService == nil {
		tsStepLogService = new(TsStepLogService)
	}
	return tsStepLogService
}

// 使用id获取数据
func (m TsStepLogService) Get(id string) *vo.TsStepLogVO {
	data := new(entity.TsStepLog)
	data.Id = id
	err := sgorm.DB.GetOne(data)
	if err != nil {
		return nil
	}
	return sc.Copy[vo.TsStepLogVO](data)
}

// 保存数据
func (m TsStepLogService) Save(dto *dto.TsStepLogDTO) error {
	data := sc.Copy[entity.TsStepLog](dto)
	data.Id = sno.GetString()
	err := sgorm.DB.Insert(data)
	return err
}

// 更新数据
func (m TsStepLogService) UpdateById(dto *dto.TsStepLogDTO) error {
	dbEntity := new(entity.TsStepLog)
	dbEntity.Id = dto.Id
	sgorm.DB.GetOne(dbEntity)
	sc.CopyTo(dto, dbEntity)
	err := sgorm.DB.UpdateById(dbEntity).Error
	return err
}

// 删除数据
func (m TsStepLogService) DeleteById(id string) error {
	err := sgorm.DB.DeleteById(entity.TsStepLog{}, id)
	return err
}

// 分页列表查询
func (m TsStepLogService) QueryPage(query *query.TsStepLogQueryDTO) *model.PageResult {
	sql := `select * from ts_step_log a  where 1=1`
	data := make([]entity.TsStepLog, 0)
	b := sbuilder.StructToBuilder(query, sql)
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, query.BaseQueryDTO.Page, sql, values...)
}

// 分页下拉查询
func (m TsStepLogService) QueryList(query *model.SelectQueryDTO) *model.PageResult {
	sql := `select a.id as value, a.task_id as label from ts_step_log a where 1=1 `
	data := make([]model.SelectVO, 0)
	b := sbuilder.Builder(sql)
	b.Like("CONCAT(a.id,a.task_id)", query.Label)
	for k, v := range query.Vars {
		b.Eq(k, v)
	}
	b.Multiple().Ors(b.In("a.id", query.Selected))
	sql, values := b.Build()
	if len(query.Selected) != 0 {
		sql += `order by a.id not in (` + strings.Join(query.Selected, ",") + `)`
	}
	return sgorm.DB.SelectPage(&data, &query.Page, sql, values...)
}
